﻿using MySql.Data.MySqlClient;
using NewChillers.Helpers;
using NewChillers.Models;
using NewChillers.Utils;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace NewChillers.ViewModels
{
    public class RecipeInfoViewModel : ObservableObject
    {
        private RecipeModel _recipe;
        private int _actType; // 操作类型  1:查看详情  2:编辑  3:新增
        private readonly Window _window;
        private readonly UserModel _currentUser;

        private bool _isDetailsEna; // 参数 是否可编辑
        private bool _isEditButtonVis; // 修改配方 按钮 是否显示
        private bool _isAddButtonVis; // 添加配方 按钮 是否显示
        private bool _isCheck1; // 流程1
        private bool _isCheck2; // 流程2

        public RecipeModel Recipe
        {
            get => _recipe;
            set => SetProperty(ref _recipe, value);
        }
        public bool IsDetailsEna
        {
            get => _isDetailsEna;
            set => SetProperty(ref _isDetailsEna, value);
        }
        public bool IsEditButtonVis
        {
            get => _isEditButtonVis;
            set => SetProperty(ref _isEditButtonVis, value);
        }
        public bool IsAddButtonVis
        {
            get => _isAddButtonVis;
            set => SetProperty(ref _isAddButtonVis, value);
        }
        public bool IsCheck1
        {
            get => _isCheck1;
            set
            {
                if (SetProperty(ref _isCheck1, value) && value)
                {
                    Recipe.RecipeProcess = 1;
                    IsCheck2 = false; // 自动取消另一个的选择
                }
            }
        }
        public bool IsCheck2
        {
            get => _isCheck2;
            set
            {
                if (SetProperty(ref _isCheck2, value) && value)
                {
                    Recipe.RecipeProcess = 2;
                    IsCheck1 = false; // 自动取消另一个的选择
                }
            }
        }

        public ICommand CloseCommand { get; } // 关闭按钮
        public ICommand UpdateRecipeCommand { get; } // 修改按钮
        public ICommand AddRecipeCommand { get; } // 添加按钮

        public RecipeInfoViewModel(RecipeModel recipe, int actType, Window window, UserModel currentUser)
        {
            _recipe = recipe;
            _actType = actType;
            _window = window;
            _currentUser = currentUser;

            CloseCommand = new RelayCommand(ExecuteClose);
            UpdateRecipeCommand = new RelayCommand(ExecuteUpdate);
            AddRecipeCommand = new RelayCommand(ExecuteAdd);

            InitThisWindowByActType(recipe, actType);


        }

        #region 添加功能
        /// <summary>
        /// 添加按钮
        /// </summary>
        private void ExecuteAdd(object obj)
        {
            if (!ValidateInput())
                return;

            try
            {
                if (AddRecipe())
                {
                    MsgBoxHelper.Success("配方添加成功");
                    _window.DialogResult = true;
                }
                else
                {
                    MsgBoxHelper.Error("配方添加失败");
                }
            }
            catch (MySqlException mysqlEx)
            {
                string friendlyMessage = mysqlEx.Number switch
                {
                    1042 => "无法连接数据库，请检查网络连接",
                    1045 => "数据库访问被拒绝",
                    1146 => "数据库表不存在",
                    1205 => "数据库操作超时，请重试", // 死锁
                    1213 => "事务死锁，请重试",      // 死锁
                    0 => "数据库连接失败，请检查网络",
                    _ => $"数据库操作失败，错误代码: {mysqlEx.Number}"
                };
                // 记录数据库异常的日志
                LogHelper.Error(this.GetType(), "[更新配方] | 数据库异常", mysqlEx, _currentUser.UserAccount);
                MsgBoxHelper.Error(friendlyMessage);
            }
            catch (Exception ex)
            {
                MsgBoxHelper.Error($"添加配方时出错：{ex.Message}");
                LogHelper.Error(this.GetType(), $"[添加配方] | 添加配方失败", ex, _currentUser.UserAccount);
            }
        }

        /// <summary>
        /// 执行添加 返回是否成功
        /// </summary>
        private bool AddRecipe()
        {
            if (IsRecipeNameExists(Recipe.RecipeName))
            {
                MsgBoxHelper.Warning("配方名称重复");
                return false;
            }

            // INSERT INTO recipe_info (recipe_name, recipe_process, cycle_count, draw_value, draw_keep_time, pump_value, pump_keep_time, stable_pressure_value, stable_pressure_keep_time, create_time, update_time, recipe_remark) VALUES(3, 3, 3, 3, 3, 3, 3, 3, 3, NOW(), NOW(), 3);
            string sql = @"INSERT INTO recipe_info 
                            (recipe_name, recipe_process, cycle_count, draw_value, draw_keep_time, pump_value, pump_keep_time, vent_value, 
                            stable_pressure_value, stable_pressure_keep_time, create_time, update_time, recipe_remark) 
                            VALUES 
                            (@RecipeName, @RecipeProcess, @CycleCount, @DrawValue, @DrawKeepTime, @PumpValue, @PumpKeepTime, 0, 
                            @StablePressureValue, @StablePressureKeepTime, NOW(), NOW(), @RecipeRemark)";

            var parameters = new[]
            {
                    new MySqlParameter("@RecipeName", Recipe.RecipeName),
                    new MySqlParameter("@RecipeProcess", Recipe.RecipeProcess),
                    new MySqlParameter("@CycleCount", Recipe.CycleCount),
                    new MySqlParameter("@DrawValue", Recipe.DrawValue),
                    new MySqlParameter("@DrawKeepTime", Recipe.DrawKeepTime),
                    new MySqlParameter("@PumpValue", Recipe.PumpValue),
                    new MySqlParameter("@PumpKeepTime", Recipe.PumpKeepTime),
                    new MySqlParameter("@StablePressureValue", Recipe.StablePressureValue),
                    new MySqlParameter("@StablePressureKeepTime", Recipe.StablePressureKeepTime),
                    new MySqlParameter("@RecipeRemark", Recipe.RecipeRemark ?? (object)DBNull.Value)
                };

            int count = MysqlHelper.ExecuteNonQuery(sql, parameters);
            return count == 1;
        }

        private bool IsRecipeNameExists(string recipeName)
        {
            string sql = "SELECT COUNT(1) FROM recipe_info WHERE recipe_name = @RecipeName";
            var parameter = new MySqlParameter("@RecipeName", recipeName);

            var result = MysqlHelper.ExecuteScalar(sql, parameter);
            return Convert.ToInt32(result) > 0;
        }
        #endregion

        #region 修改功能
        /// <summary>
        /// 修改按钮
        /// </summary>
        private void ExecuteUpdate(object obj)
        {
            if (!ValidateInput())
                return; // 验证失败，提前退出

            // 验证通过，执行修改逻辑
            try
            {
                // 是否成功
                if (UpdateRecipe())
                {
                    MsgBoxHelper.Success("配方更新成功");
                    _window.DialogResult = true; // 设置成功结果
                }
                else
                {
                    MsgBoxHelper.Error("配方更新失败");
                }
            }
            catch (MySqlException mysqlEx)
            {
                string friendlyMessage = mysqlEx.Number switch
                {
                    1042 => "无法连接数据库，请检查网络连接",
                    1045 => "数据库访问被拒绝",
                    1146 => "数据库表不存在",
                    1205 => "数据库操作超时，请重试", // 死锁
                    1213 => "事务死锁，请重试",      // 死锁
                    0 => "数据库连接失败，请检查网络",
                    _ => $"数据库操作失败，错误代码: {mysqlEx.Number}"
                };
                // 记录数据库异常的日志
                LogHelper.Error(this.GetType(), "[更新配方] | 数据库异常", mysqlEx, _currentUser.UserAccount);
                MsgBoxHelper.Error(friendlyMessage);
            }

            catch (Exception ex)
            {
                MsgBoxHelper.Error($"更新配方时出错：{ex.Message}");
                LogHelper.Error(this.GetType(), $"[更新配方] | 更新配方失败 配方编号:{Recipe.RecipeId}", ex, _currentUser.UserAccount);
            }
        }

        /// <summary>
        /// 执行修改 返回是否成功
        /// </summary>
        private bool UpdateRecipe()
        {
            string sql = @"UPDATE recipe_info 
                                SET recipe_name = @RecipeName,
                                recipe_process = @RecipeProcess,
                                cycle_count = @CycleCount,
                                draw_value = @DrawValue,
                                draw_keep_time = @DrawKeepTime,
                                pump_value = @PumpValue,
                                pump_keep_time = @PumpKeepTime,
                                stable_pressure_value = @StablePressureValue,
                                stable_pressure_keep_time = @StablePressureKeepTime,
                                recipe_remark = @RecipeRemark,
                                update_time = NOW() 
                                WHERE recipe_id = @RecipeId";

            var parameters = new[]
            {
                    new MySqlParameter("@RecipeName", Recipe.RecipeName),
                    new MySqlParameter("@RecipeProcess", Recipe.RecipeProcess),
                    new MySqlParameter("@CycleCount", Recipe.CycleCount),
                    new MySqlParameter("@DrawValue", Recipe.DrawValue),
                    new MySqlParameter("@DrawKeepTime", Recipe.DrawKeepTime),
                    new MySqlParameter("@PumpValue", Recipe.PumpValue),
                    new MySqlParameter("@PumpKeepTime", Recipe.PumpKeepTime),
                    new MySqlParameter("@StablePressureValue", Recipe.StablePressureValue),
                    new MySqlParameter("@StablePressureKeepTime", Recipe.StablePressureKeepTime),
                    new MySqlParameter("@RecipeRemark", Recipe.RecipeRemark ?? (object)DBNull.Value),
                    new MySqlParameter("@RecipeId", Recipe.RecipeId)
                };

            int count = MysqlHelper.ExecuteNonQuery(sql, parameters);
            return count == 1;
        }
        #endregion

        /// <summary>
        /// 关闭这个小窗口
        /// </summary>
        private void ExecuteClose(object obj)
        {
            _window.DialogResult = false; // 设置取消结果
        }

        /// <summary>
        /// 初始化 By 操作类型
        /// </summary>
        private void InitThisWindowByActType(RecipeModel recipe, int actType)
        {
            // 根据 RecipeProcess 初始化 RadioButton 状态
            if (recipe != null)
            {
                _isCheck1 = recipe.RecipeProcess == 1;
                _isCheck2 = recipe.RecipeProcess == 2;
            }

            if (actType == 1) // 查看详情
            {
                IsDetailsEna = false;
                IsEditButtonVis = false;
                IsAddButtonVis = false;
            }
            else if (actType == 2) // 修改
            {
                IsDetailsEna = true;
                IsEditButtonVis = true;
                IsAddButtonVis = false;
            }
            else if (actType == 3) // 添加
            {
                IsDetailsEna = true;
                IsEditButtonVis = false;
                IsAddButtonVis = true;
            }
            else
            {
                Debug.WriteLine("操作 [配方管理] 失败");
                MsgBoxHelper.Info("操作 [配方管理] 失败，未知操作类型");
                LogHelper.Info(this.GetType(), "[配方管理] | 操作 [配方管理] 失败，识别到未知操作类型", _currentUser.UserAccount);
                _window.DialogResult = false; // 设置取消结果
            }
        }

        /// <summary>
        /// 输入验证
        /// </summary>
        private bool ValidateInput()
        {
            // 检查空值
            if (string.IsNullOrEmpty(Recipe.RecipeName))
            {
                MsgBoxHelper.Warning("请输入配方名");
                return false;
            }
            if (Recipe.RecipeProcess != 1 && Recipe.RecipeProcess != 2)
            {
                MsgBoxHelper.Warning("请选择目标流程");
                return false;
            }
            if (Recipe.CycleCount == 0)
            {
                MsgBoxHelper.Warning("循环次数不能为0");
                return false;
            }
            if (string.IsNullOrEmpty(Recipe.DrawValue))
            {
                MsgBoxHelper.Warning("请输入抽真空压力");
                return false;
            }
            if (Recipe.DrawKeepTime == 0)
            {
                MsgBoxHelper.Warning("真空保持时间不能为0");
                return false;
            }
            if (string.IsNullOrEmpty(Recipe.PumpValue))
            {
                MsgBoxHelper.Warning("请输入充气压力");
                return false;
            }
            if (Recipe.PumpKeepTime == 0)
            {
                MsgBoxHelper.Warning("充气保持时间不能为0");
                return false;
            }
            if (string.IsNullOrEmpty(Recipe.StablePressureValue))
            {
                MsgBoxHelper.Warning("请输入稳压压力");
                return false;
            }
            if (Recipe.StablePressureKeepTime == 0)
            {
                MsgBoxHelper.Warning("稳压保持时间不能为0");
                return false;
            }

            // 逻辑



            return true;
        }
    }
}
